package com.example.forum.controller;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.forum.MyQuery;
import com.example.forum.commons.jwt.JwtHelper;
import com.example.forum.commons.jwt.JwtTokenResult;
import com.example.forum.commons.jwt.LoginUserModel;
import com.example.forum.commons.tools.StringUtil;
import com.example.forum.commons.tools.Transfer.DataTransfer;
import com.example.forum.entity.*;
import com.example.forum.service.*;
import com.example.forum.vo.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.example.forum.commons.tools.Utils.md5Encoding;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author why
 * @since 2020-04-22
 */
@RestController
@RequestMapping("AppUser")
public class TAppuserController extends BaseController {
    @Autowired
    ITAppuserService appuserService;

    @Autowired
    ITStreetService streetService;

    @Autowired
    ITJuweiService juweiService;

    @Autowired
    ITRegionService regionService;

    @Autowired
    private ITUserrolesService userrolesService;

    @Autowired
    private ITUsersService usersService;

    @Autowired
    private DataTransfer dataTransfer;

    @Autowired
    private ITRolesService rolesService;

    @Autowired
    JwtHelper jwtHelper;


    @GetMapping("GetNewAppUser")
    public JsonResult getNewAppUser(@RequestParam(defaultValue = "1") Integer pageIndex,
                                    @RequestParam(defaultValue = "10") Integer pageSize,
                                    @RequestParam(defaultValue = "") String NameOrPhone,
                                    @RequestParam(defaultValue = "null") String Status, Integer Day2) {
        DateTime date = DateUtil.date(Calendar.getInstance());
        MyQuery<TAppuser> query = new MyQuery<>();
        query.and(
                wrapper -> wrapper.like("UserName", "%" + NameOrPhone + "%").or().like("Phone", "%" + NameOrPhone + "%")
        ).ne("Address", "");
        if (!"null".equals(Status))
            query.eq("status", Status);
        if (Day2 != null)
            query.between("CreationTime", DateUtil.offset(date, DateField.DAY_OF_MONTH, -Day2), date);
        //获取用户角色
        List<String> roleIds = userrolesService.getUserRoles(currentUserId());
        for (String roleId : roleIds) {
            TRoles role = rolesService.getById(roleId);
            if (role != null) {
                TUsers user = usersService.getById(currentUserId());
                if (role.getName().equals("街道管理员")) {
                    query.eq("StreetId", user.getStreetid());
                }
                if (role.getName().equals("居委管理员")) {
                    query.eq("NeighborhoodCommitteeId", user.getNeighborhoodcommitteeid());
                }
            }
        }
        IPage<TAppuser> pageData = appuserService.page(new Page<>(pageIndex, pageSize), query);
        for (TAppuser appUser : pageData.getRecords()) {
            appuserService.getUserAddress(appUser);
            appUser.setPassword(null);
            appUser.setSmY_Statue("0");
            appUser.setSalt(null);
        }
        return new JsonResult(HttpStatus.OK, "成功", new PageDto(pageData.getTotal(), pageData.getRecords()));
    }

    /**
     * 委任用户  获取用户列表
     * @param pageIndex     页码
     * @param pageSize      每页数目
     * @param nameOrPhone   姓名电话
     * @param appointStatus 状态
     * @param day2          日期范围 int
     * @return
     */
    @GetMapping("GetAppointList")
    public JsonResult getAppointList(@RequestParam(defaultValue = "1") Integer pageIndex,
                                     @RequestParam(defaultValue = "10") Integer pageSize,
                                     @RequestParam(value = "NameOrPhone", defaultValue = "") String nameOrPhone,
                                     @RequestParam("AppointStatus") String appointStatus,
                                     @RequestParam("Day2") Integer day2) {

        DateTime date = DateUtil.date(Calendar.getInstance());
        MyQuery<TAppuser> query = new MyQuery<>();
        query.and(
                wrapper -> wrapper.like("UserName", "%" + nameOrPhone + "%").or().like("Phone", "%" + nameOrPhone + "%")
        ).ne("Address", "");
        if (!"null".equals(appointStatus))
            query.eq("appointStatus", appointStatus);
        if (day2 != null)
            query.between("CreationTime", DateUtil.offset(date, DateField.DAY_OF_MONTH, -day2), date);
        //获取用户角色
        List<String> roleIds = userrolesService.getUserRoles(currentUserId());
        for (String roleId : roleIds) {
            TRoles role = rolesService.getById(roleId);
            if (role != null) {
                TUsers user = usersService.getById(currentUserId());
                if (role.getName().equals("街道管理员")) {
                    query.eq("StreetId", user.getStreetid());
                }
                if (role.getName().equals("居委管理员")) {
                    query.eq("NeighborhoodCommitteeId", user.getNeighborhoodcommitteeid());
                }
            }
        }
        IPage<TAppuser> pageData = appuserService.page(new Page<>(pageIndex, pageSize), query);
        for (TAppuser appUser : pageData.getRecords()) {
            appuserService.getUserAddress(appUser);
            appUser.setPassword(null);
            appUser.setSmY_Statue("0");
            appUser.setSalt(null);
        }
        return new JsonResult(HttpStatus.OK, "成功", new PageDto(pageData.getTotal(), pageData.getRecords()));
    }



    /**
     * 后台审核
     *
     * @param AppUserId
     * @param Status
     * @return
     */
    @GetMapping("doAudit")
    public JsonResult doAudit(String AppUserId, Integer Status) {
        TAppuser appuser = new TAppuser();
        appuser.setId(AppUserId);
        appuser.setStatus(Status);
        if (appuserService.updateById(appuser))
            return new JsonResult(HttpStatus.OK, "审核成功", null);
        else
            return new JsonResult(HttpStatus.INTERNAL_SERVER_ERROR, "审核失败", null);
    }

    @PostMapping("IsProhibit")
    public JsonResult isProhibit(String AppUserId, boolean IsProhibit, Integer expirationDate) {
        TAppuser appuser = new TAppuser();
        appuser.setId(AppUserId);
        appuser.setIsprohibit(IsProhibit);

        if (IsProhibit) {
            Map<Integer, Integer> disableTime = DisableTimes.getDisableTime();
            Integer disableDay = disableTime.get(expirationDate);
            if (disableDay != null)
                appuser.setExpirationdate(DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, disableDay));
            else
                return new JsonResult(HttpStatus.INTERNAL_SERVER_ERROR, "更新失败", null);
        } else {
            appuser.setExpirationdate(null);
        }

        if (appuserService.updateById(appuser))
            return new JsonResult(HttpStatus.OK, "更新成功", null);
        else
            return new JsonResult(HttpStatus.INTERNAL_SERVER_ERROR, "更新失败", null);
    }

    @GetMapping("GetUserInfo")
    public JsonResult getUserInfo(String UserName) {
        TAppuser user = appuserService.getOne(new MyQuery<TAppuser>().eq("UserName", UserName));
        user.setPassword(null);
        user.setSalt(null);
        if (user == null)
            return new JsonResult(HttpStatus.NOT_MODIFIED, "用户不存在", null);
        else {
            appuserService.getUserAddress(user);
            return new JsonResult(HttpStatus.OK, "成功", user);
        }
    }


    /**
     * 委任、撤销用户
     *
     * @param doAppoint
     * @return
     */
    @PostMapping("doAppoint")
//    public JsonResult doAppoint( String AppUserId,Integer AppointStatus, String Role)  {
    public JsonResult doAppoint(@RequestBody DoAppoint doAppoint) {

        //当前用户id
        CurrentUser currentUser = currentUser();
        String currentUserId = currentUser.getId();
        return appuserService.daAppointUser(doAppoint, currentUserId);

    }

    @PostMapping("DeleteAppUser")
      public JsonResult DeleteAppUser(String AppUserId){
//    public JsonResult DeleteAppUser(@RequestBody DoAppoint doAppoint) {
//        String AppUserId = doAppoint.getAppUserId();
        TAppuser appUserById = appuserService.getById(AppUserId);
        TAppuser tAppuser = appUserById.setIsdeleted(true);
        if (appuserService.updateById(appUserById)) {
            return new JsonResult(HttpStatus.OK, "删除成功", null);
        }
        return new JsonResult(HttpStatus.BAD_REQUEST, "删除失败", null);
    }

    @PostMapping("login")
    public JsonResult login(String PhoneOrName,String PassWord){
        if (StringUtil.isEmpty(PhoneOrName) || StringUtil.isEmpty(PassWord)) {
            return new JsonResult(HttpStatus.FORBIDDEN,"用户名密码不能为空",null);
        }
        TAppuser appUser = appuserService.getOne(new MyQuery<TAppuser>().eq("username", PhoneOrName));
        if (appUser==null) {
            return new JsonResult(HttpStatus.NOT_FOUND,"用户不存在",null);
        }
        String md5Psw = md5Encoding(md5Encoding(PassWord) + appUser.getSalt());
        if (md5Psw.equals(appUser.getPassword())) {
            appuserService.getUserAddress(appUser);
            JwtTokenResult jwtTokenResult = jwtHelper.generateToken(
                    new LoginUserModel(appUser.getId(), appUser.getUsername(),appUser.getRealname(),"","","")
            );
            appUser.setToken(jwtTokenResult.getAccess_token());
            return new JsonResult(HttpStatus.OK,"成功",appUser);
        }

        return new JsonResult(HttpStatus.NOT_ACCEPTABLE,"用户名或密码错误",null);
    }

    /**
     * 完善注册信息
     * @param appuser
     * @return
     */
    @PostMapping("PerfectAppUser")
    public JsonResult PerfectAppUser(@RequestBody TAppuser appuser){
        if (StringUtil.isEmpty( appuser.getRealname() ) || StringUtil.isEmpty(appuser.getIdcard()) ||
        StringUtil.isEmpty( appuser.getPhone() ) || StringUtil.isEmpty(appuser.getStreetid()) ||
        StringUtil.isEmpty(appuser.getRegionid()) || StringUtil.isEmpty(appuser.getNeighborhoodcommitteeid())) {
            return new JsonResult(HttpStatus.NOT_ACCEPTABLE,"请输入完整信息",null);
        }
        appuser.setStatus(3);
        boolean flag = appuserService.update(appuser, new QueryWrapper<TAppuser>().eq("username", appuser.getUsername()));
        if (flag)
            return new JsonResult(HttpStatus.OK,"完善信息成功",appuserService.getOne(new QueryWrapper<TAppuser>().eq("username", appuser.getUsername())));
        else
            return new JsonResult(HttpStatus.NOT_FOUND,"用户不存在",null);
    }
}
